package com.csx.stack;

import com.csx.linkedlist.LinkedList;

/**
 * 链表实现栈   链表栈比数组栈 要快一些  因为数组栈要自动扩容   但是数量到了100000的时候比数组要慢  因为new node对象  越多耗时约大
 * @author 陈胤训
 * <p>
 * create: 2019-05-05 10:57
 **/
public class LinkedListStack<E> implements Stack<E> {

    private LinkedList<E> list;

    private LinkedListStack(){
        list = new LinkedList<E>();
    }

    @Override
    public int getSize() {
        return list.getSize();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void push(E e) {
        list.addFirst(e);
    }

    @Override
    public E pop() {
        return list.removeFirst();
    }

    @Override
    public E peek() {
        return list.getFirst();
    }

    /**
     * 重写toString方法
     * @return
     */
    @Override
    public String toString(){
        StringBuilder builder = new StringBuilder();
        builder.append("Stack: top");
        builder.append(list);
        return builder.toString();
    }

    public static void main(String[] args) {
        LinkedListStack<Integer> arrayStack = new LinkedListStack<>();

        for (int i = 0; i < 5; i++) {
            arrayStack.push(i);
            System.out.println(arrayStack.toString());
        }
        arrayStack.pop();
        System.out.println(arrayStack);

    }
}
